#include "getvideothread.h"

#include <QTimer>
#include <QDebug>
#include <QImage>

#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/opencv.hpp>

GetVideoThread::GetVideoThread(QObject *parent)
{

}

void GetVideoThread::run()
{
    qDebug() << "拉流Thread启动";
    QString url = "http://192.168.1.100:8080/?action=stream";
    cv::VideoCapture *cap = new cv::VideoCapture(url.toStdString());

    if (!cap->isOpened()) {
        qDebug() << "Failed to open stream.";
        return;
    }

//    QTimer *timer = new QTimer();
//    connect(timer, &QTimer::timeout, [=]() {
//        cv::Mat frame;
//        (*cap) >> frame;
//        if (frame.empty()) {
//            timer->stop();
//            return;
//        }

//        QImage image(frame.data, frame.cols, frame.rows, frame.step, QImage::Format_RGB888);
//        showImage(image.rgbSwapped());
//        // 触发信号，将图片image返回回去
//        emit imgReturned(&image);
//    });

//    timer->start(33); // 每33ms获取一帧图像，约30帧每秒

    while(1) {
        cv::Mat frame;
        (*cap) >> frame;
//        qDebug() << "获得视频帧frame";
        if (frame.empty()) {
            qDebug() << "没有获得视频帧frame";
            return;
        }

        QImage image(frame.data, frame.cols, frame.rows, frame.step, QImage::Format_RGB888);
//        QImage image = QImage(frame.data, frame.cols, frame.rows, frame.step, QImage::Format_RGB888);

        // showImage(image.rgbSwapped());
        // 触发信号，将图片image返回回去
        // 将rgb通道进行反转
        QImage *img = new QImage(image.rgbSwapped());
        emit imgReturned(img);

        QThread::msleep(33);
    }


}
